package com.yanwq.simpleapplib.http.client;

import android.os.Handler;
import android.os.Looper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 作者：闫伟强。
 * 日期：2016/6/20。
 */
public abstract class OkFileResponseCallback implements OkResponseCallback {
    Call call;
    Handler mHandler;
    File file;

    public OkFileResponseCallback(File file) {
        this.file = file;
        mHandler = new Handler(Looper.getMainLooper());
    }

    public void setCall(Call call) {
        this.call = call;
    }

    @Override
    public void onSuccess(int status, Headers headers, Object obj) {
        onSuccess((File) obj);
    }

    public abstract void onSuccess(File file);

    public abstract void onProgress(long currentLength, long totalLength);

    @Override
    public File parse(Response response) {
        final ResponseBody body = response.body();

        if (file.exists()) {
            if (file.length() == body.contentLength()) {
                call.cancel();
                return file;
            } else {
                if (!file.delete()) {
                    throw new RuntimeException("Can't delete old file");
                }
            }
        }

        final long totalLen = body.contentLength();
        byte[] bytes = new byte[1024];
        int count;
        long sumCount = 0;
        InputStream inputStream = body.byteStream();

        try {
            OutputStream outputStream = new FileOutputStream(file);
            while ((count = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, count);
                sumCount += count;
                final long currentLen = sumCount;

                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        onProgress(currentLen, totalLen);
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return file;
    }
}
